/* eslint-disable no-nested-ternary */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Row, Input, Button, Col, Checkbox, Icon, InputNumber, Divider, Form, Radio } from 'antd';
import { numberToChar } from '@/utils/utils';

const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

@connect(({ paper }) => ({

}))
@Form.create()
class QuestionSetting extends PureComponent {

  constructor(...args) {
    super(...args);
    const { question } = this.props;
    this.state = {
      analysisItem: question.analysis!==null ? true : false
    };
  }

  handleSubmit = (e) => {
    const { form, dispatch, question, hideConponent } = this.props;
    console.log("e", e);
    form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        dispatch({
          type: 'paper/setExamQuestion',
          payload: {
            id: question.id,
            columnId: question.columnId,
            ...values,
          },
          callback: (res)=>{
            if(res){
              hideConponent();
            }
          }
        });
      }
    });
  }

  handleCancel = () => {
    this.props.hideConponent();
  }

  formRemove = (k) => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    // We need at least one passenger
    if (keys.length === 2) {
      return;
    }
    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  }

  formAdd = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    if (keys.length < 1) {
      const nextKeys = [0];
      // can use data-binding to set
      // important! notify form to detect changes
      form.setFieldsValue({
        keys: nextKeys,
      });
    } else {
      const nextKeys = keys.concat(keys[keys.length - 1] + 1);
      // can use data-binding to set
      // important! notify form to detect changes
      form.setFieldsValue({
        keys: nextKeys,
      });
    }

  }

  addOrRemoveAnalysis = () => {
    const { analysisItem } = this.state;
    this.setState({
      analysisItem: analysisItem===true ? false : true
    })
  }

  chooseType = (e) => {
    console.log(`radio checked:${e.target.value}`);
  }


  render() {
    const {
      form: { getFieldDecorator, getFieldValue }, question
    } = this.props;
    const { analysisItem } = this.state;

    const childFormItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
        md: { span: 19 },
      },
    };

    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 19, offset: 3 },
      },
    };


    getFieldDecorator('keys', { initialValue: [] });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => (
      <FormItem
        {...(index === 0 ? childFormItemLayout : formItemLayoutWithOutLabel)}
        label={index === 0 ? '选项' : ''}
        required
        key={k}
      >
        {getFieldDecorator(`option[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [{
            required: true
          }],
        })(
          <Input
            style={{ width: `90%` }}
            addonBefore={numberToChar(k)}
          />
        )}
        {k === keys[keys.length - 1] ? (
          <Icon
            // className="dynamic-delete-button"
            type="minus-circle-o"
            disabled={keys.length === 2}
            onClick={() => this.formRemove(k)}
            style={{ marginLeft: 10 }}
          />
        ) : null}
      </FormItem>
    ))

    const answerItems = keys.map((k, index) => (
      <Col sm={2} md={2}><Checkbox value={k} key={k}>{numberToChar(k)}</Checkbox></Col>
    ))

    return (
      <div>
        <Card
          headStyle={{ backgroundColor: `#EEEEEE` }}
          bodyStyle={{ backgroundColor: `#fefcf7` }}
        // title="栏目标题"
        // extra={<Button><Icon type="plus" />添加新题</Button>}
        >
          <Form {...childFormItemLayout}>
            <FormItem label="题干">
              {getFieldDecorator('title', {
                rules: [
                  {
                    required: true,
                  },
                ],
                initialValue: question.title,
              })(<Input />)}
            </FormItem>
            {/* <FormItem label="知识点">
              {getFieldDecorator('knowledage', {
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Input />)}
            </FormItem> */}
            <FormItem label="分值">
              {getFieldDecorator('value', {
                rules: [
                  {
                    required: true,
                    type: "number",
                    min: 1,
                    max: 100,
                  },
                ],
                initialValue: question.value,
              })(<InputNumber />)}
            </FormItem>
            <FormItem label="题型">
              {getFieldDecorator('type', {
                rules: [
                  {
                    required: true,
                  },
                ],
                initialValue: question.type.toString(),
              })(
                <RadioGroup onChange={this.chooseType}>
                  {/* <RadioButton value="1">选择题</RadioButton>
                  <RadioButton value="3">填空题</RadioButton>
                  <RadioButton value="4">判断题</RadioButton> */}
                  <RadioButton value="5">上传题</RadioButton>
                </RadioGroup>)}
            </FormItem>
            {
              getFieldValue('type') === '1' ?
                <div>
                  {formItems}
                  <FormItem {...formItemLayoutWithOutLabel}>
                    <Button type="dashed" onClick={this.formAdd} style={{ width: '40%' }}>
                      <Icon type="plus" />添加一级选项
                    </Button>
                  </FormItem>
                  <FormItem label="答案">
                    {getFieldDecorator("answer", {
                      rules: [
                        {
                          required: true,
                        },
                      ],
                    })(
                      <Checkbox.Group style={{ width: "100%", marginTop: 10 }}>
                        <Row>
                          {answerItems}
                        </Row>
                      </Checkbox.Group>
                    )}
                  </FormItem>
                </div>
                :
                getFieldValue('type') === '3' ?
                  <FormItem label="答案">
                    {getFieldDecorator('answer', {
                      rules: [
                        {
                          required: true,
                        },
                      ],
                    })(<Input />)}
                  </FormItem>
                  :
                  getFieldValue('type') === '4' ?
                    <FormItem label="答案" >
                      {getFieldDecorator("answer", {
                        rules: [
                          {
                            required: true,
                          },
                        ],
                      })(
                        <RadioGroup>
                          <RadioButton value="true">正确</RadioButton>
                          <RadioButton value="false">错误</RadioButton>
                        </RadioGroup>
                      )}
                    </FormItem>
                    :
                    getFieldValue('type') === '5' ?
                      <FormItem label="答案">
                        {getFieldDecorator('answer', {
                          initialValue: question.answer&&question.answer
                        })(<Input.TextArea autosize={{ maxRows: 5, minRows: 2 }} />)}
                      </FormItem>
                      : null}
            <FormItem label="解析">
              {
                analysisItem ?
                  <Row>
                    <Col xs={7} md={20}>
                      {getFieldDecorator("analysis", {
                        initialValue: question.analysis&&question.analysis
                      })(<Input.TextArea autosize={{ minRows: 3, maxRows: 6 }} />)}
                    </Col>
                    <Col xs={2} md={2}><Icon
                      // className="dynamic-delete-button"
                      type="minus-circle-o"
                      onClick={this.addOrRemoveAnalysis}
                      style={{ marginLeft: 10 }}
                    />
                    </Col>
                  </Row> :
                  <Button type="dashed" style={{ width: '40%' }} onClick={this.addOrRemoveAnalysis}>
                    <Icon type="plus" />添加解析
                  </Button>
              }
            </FormItem>
            <FormItem {...formItemLayoutWithOutLabel}>
              <Row type="flex" justify="center" gutter={24}>
                <Col>
                  <Button onClick={this.handleCancel}>取消</Button>
                </Col>
                <Col>
                  <Button type="primary" onClick={this.handleSubmit} htmlType="submit">确定</Button>
                </Col>
              </Row>

            </FormItem>
          </Form>
        </Card>
      </div>
    )
  }
}
export default QuestionSetting